/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package cn.slb.im.modules.sys.controller;

import cn.slb.im.common.utils.R;
import cn.slb.im.modules.app.entity.UserEntity;
import cn.slb.im.modules.sys.biz.AccessTokenBiz;
import cn.slb.im.modules.sys.biz.impl.AccessTokenBizImpl;
import cn.slb.im.modules.sys.config.WorkWxConfig;
import cn.slb.im.modules.sys.constant.WorkWxConstant;
import cn.slb.im.modules.sys.dto.WxLoginUserDTO;
import cn.slb.im.modules.sys.entity.SysUserEntity;
import cn.slb.im.modules.sys.enums.LoginEnum;
import cn.slb.im.modules.sys.form.SysLoginForm;
import cn.slb.im.modules.sys.form.SysLoginWxForm;
import cn.slb.im.modules.sys.service.SysCaptchaService;
import cn.slb.im.modules.sys.service.SysUserService;
import cn.slb.im.modules.sys.service.SysUserTokenService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private AccessTokenBiz accessTokenBiz;
	@Autowired
	private WorkWxConfig workWxConfig;
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		// 设置登录状态为 ： 已登录
		sysUserService.updateLoginStatus(user.getUserId(), LoginEnum.ONLINE.getCode());

		//生成token，并保存到数据库
		return sysUserTokenService.createToken(user.getUserId());
	}

	@PostMapping("/sys/login/wx")
	public Map<String, Object> loginWx(@RequestBody SysLoginWxForm form)throws IOException {
		// accessToken
		String accessToken = accessTokenBiz.getAccessToken();
		// 获取访问用户身份
		// https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE
		String userIdUrl = workWxConfig.getBaseUrl() + String.format(WorkWxConstant.GET_USERID, accessToken, form.getCode());
		Map map = restTemplate.getForObject(userIdUrl, Map.class);
		if (CollectionUtils.isEmpty(map)) {
			throw new RuntimeException("获取企业微信用户身份失败，失败原因：网络出小差了，请稍后再试");
		}
		if (0 != (int) map.get("errcode")) {
			throw new RuntimeException("获取企业微信用户身份失败，失败原因：" + map.get("errmsg"));
		}
		String userId = (String) map.get("UserId");
		log.info("userID:{}", userId);
		// 读取成员
		// https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
		String userUrl = workWxConfig.getBaseUrl() + String.format(WorkWxConstant.GET_USER, accessToken, userId);
//		Map userMap = restTemplate.getForObject(userUrl, WxUs.class);
		WxLoginUserDTO userDTO = restTemplate.getForObject(userUrl, WxLoginUserDTO.class);
		log.info("user info :{}" , JSON.toJSONString(userDTO));

		SysUserEntity user = sysUserService.queryByUserName(userDTO.getUserid());
		if(ObjectUtils.isEmpty(user)){
			user = new SysUserEntity();
			user.setUsername(userDTO.getUserid());
			user.setMobile(userDTO.getMobile());
			user.setEmail(userDTO.getEmail());
			user.setPassword(workWxConfig.getInitPass());
			user.setStatus(1);
			user.setCreateUserId(1L);
			List<Long> roles = new ArrayList<>(1);
			roles.add(2L);
			user.setRoleIdList(roles);
			sysUserService.saveUser(user);
		}
		user = sysUserService.queryByUserName(userDTO.getUserid());

		// 设置登录状态为 ： 已登录
		sysUserService.updateLoginStatus(user.getUserId(), LoginEnum.ONLINE.getCode());

		//生成token，并保存到数据库
		return sysUserTokenService.createToken(user.getUserId());
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		// 修改token
		sysUserTokenService.logout(getUserId());
		// 设置登录状态为 ： 未登录
		sysUserService.updateLoginStatus(getUserId(), LoginEnum.NO_ONLINE.getCode());
		return R.ok();
	}

}
